package com.anycl.customer.servlet.user;

import com.anycl.customer.entity.AdminUser;
import com.anycl.customer.exception.CustomerException;
import com.anycl.customer.service.AdminUserService;
import com.anycl.customer.service.impl.AdminUserServiceImpl;
import com.anycl.customer.vo.UserVo;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/login")
@Slf4j
public class UserLoginServlet extends HttpServlet {
    private AdminUserService adminUserService;
    @Override
    public void init() throws ServletException {
        adminUserService = new AdminUserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("/user/login  doPost()");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        AdminUser user = new AdminUser();
        user.setUsername(username);
        user.setPassword(password);
        try {
            UserVo vo = adminUserService.login(user, req.getSession());
            resp.getWriter().write(vo.getUsername() + " 登录成功 " );
        } catch (CustomerException e) {
            resp.getWriter().write("error: " + e.getMessage());
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        if (method.equalsIgnoreCase("get")) {
            doGet(req, resp);
        } else {
            doPost(req, resp);
        }
    }
}
